<template>
	<view>
		<view v-if="login == true">
			<view class="title">
				<view class="lose" @tap="changeCategory" data-category="1">
					寻失主
					<view :class="item.category == 1 ? 'line' : ''"></view>
				</view>
				<view class="seek" @tap="changeCategory" data-category="0">
					寻失物
					<view :class="item.category == 0 ? 'line' : ''"></view>
				</view>
				<!-- <view class="reset" bind:tap="reset">
        <image src="https://xunhang.oss-cn-beijing.aliyuncs.com/static/reset.png" mode=""/>
    </view> -->
			</view>

			<!-- 必填 -->
			<view class="content">
				<!-- 1. 发布标题 -->
				<view class="title">
					<input type="text" placeholder="输入发布标题" maxlength="15" v-model="item.title" />
				</view>

				<!-- 物品种类 -->
				<view class="tag-list">
					<!-- 比较多的几个 -->
					<view :class="index == tagindex ? 'tag1' : 'tag'" :data-index="index" @tap="changeTag"
						v-for="(item, index) in tags" :key="index">
						{{ tags[index] }}
					</view>

					<!-- 可供选择的标签 -->
					<picker :class="tagindex == -1 ? 'tag1' : 'tag'" @change="changePickTag" mode="selector"
						:value="tagpickindex" :range="picktags" header-text="物品种类">
						{{ picktags[tagpickindex] }}
					</picker>
				</view>
				<!-- /物品种类end -->

				<!-- 物品描述/位置 -->
				<view class="text">
					<view class="textFont">备注 丨</view>
					<input type="text" placeholder="请简述该物品的信息" v-model="item.description" />
				</view>
				<!-- 物品描述end -->

				<!-- 提示 -->
				<view class="tip">*以上为必填项</view>
			</view>

			<view class="addImg">
				<view class="add" v-for="(item, index) in images" :key="index">
					<image :src="images[index]" mode="" />

					<view class="del-icon">
						<image src="https://xunhang.oss-cn-beijing.aliyuncs.com/static/del.png" @tap="deleteImage" />
					</view>
				</view>
				<view v-if="images.length < 4" class="add" @tap="chooseImage">+</view>
			</view>
			<view class="tip-image">上传图片</view>

			<!-- 补充项 对寻找失物的用户 -->

			<view class="supplement">
				<view class="tip">*补充项</view>
				<view class="location">
					<input v-if="item.category == 0" type="text" v-model="item.location" placeholder="丢失位置" />
					<input v-else type="text" v-model="item.location" placeholder="拾获位置" />
				</view>
				<picker class="date" mode="date" :value="item.date" :end="now" @change="changedate">
					{{ item.date }}
				</picker>
			</view>

			<!-- 提交按钮 -->
			<view class="submitButton" @tap="submitform">发布</view>
		</view>

		<view v-else>
			<notlogin></notlogin>
		</view>
	</view>
</template>

<script>
	import UNI_APP from '@/.env.js'
	const baseUrl = UNI_APP.BASE_URL


	const app = getApp();
	export default {

		data() {
			return {
				tags: ['耳机', '书本', '水杯', '证件'],
				picktags: ['其他', '手机', '钥匙', '钱包', '相机', '衣服', '首饰'],
				item: {
					title: '',
					description: '',
					location: '',
					date: '',
					category: false,
					tag: '其他',
					images: []
				},
				tagindex: -1,
				//初始化为-1
				tagpickindex: 0,
				images: [],
				now: new Date(),
				login: false
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			console.log(options.category);
			var category = options.category == 'false' ? false : true; //接受页面参数
			var item = this.item;
			var date = item.category === false ? '选择丢失时间' : '选择拾获时间';

			this.item.date = date,
				this.item.category = category == null ? item.category : category,
				this.login = uni.getStorageSync('user') == null ? false : true

		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage() {},
		methods: {
			// 双向绑定寻找类别
			changeCategory: function(e) {
				var category = e.target.dataset.category;
				console.log('category发生change事件，携带category值为：', category);
				var date = new String();
				if (category == 0) {
					date = '选择丢失时间';

				} else {
					date = '选择拾获时间';
				}
				this.item.category = category == 0 ? false : true,
					this.item.date = date
			},

			// 选择丢失时间
			changedate(e) {
				console.log('选择丢失时间:', e.detail.value);
				this.item.date = e.detail.value

			},

			// 选择标签
			changeTag(e) {
				console.log(e);
				var tags = this.tags;
				var index = e.currentTarget.dataset.index;
				var tag = tags[index];

				this.item.tag = tag,
					this.tagindex = index

			},

			changePickTag(e) {
				console.log(e);
				var tagpickindex = e.detail.value;
				var picktags = this.picktags;
				var tag = picktags[tagpickindex];

				this.tagpickindex = tagpickindex,
					this.item.tag = tag,
					this.tagindex = -1

			},

			// 上传图片
			chooseImage() {
				if (this.images.length >= 6) {
					uni.showToast({
						title: '不能超过6张'
					});
				} else {
					uni.chooseMedia({
						count: 6 - this.images.length,
						mediaType: ['image'],
						sourceType: ['album', 'camera'],
						sizeType: ['compressed'],
						success: (res) => {
							const images = this.images;
							for (let i = 0; i < res.tempFiles.length; i++) {
								images.push(res.tempFiles[i].tempFilePath);
							}

							this.images = images

						}
					});
				}
			},

			//  删除图片
			deleteImage(e) {
				console.log(e);
				const index = e.currentTarget.dataset.index;
				const images = this.images;
				images.splice(index, 1);
				this.images = images

			},

			//重置
			reset() {

				this.item.title = ''
				this.item.description = ''
				this.item.location = ''
				this.item.data = new Date()
				this.item.tag = '其他'
				this.item.images = []
				this.tagindex = -1,
					//初始化为-1
					this.tagpickindex = 0,
					this.images = []

			},

			uploadImage(images) {
				const promiseArr = []
				for (let i = 0; i < images.length; i++) {
					promiseArr.push(new Promise((resolve, reject) => {
						uni.uploadFile({
							url: UNI_APP.BASE_URL + '/file/uploadImage/itemImage',
							header: {
								accessToken: uni.getStorageSync("loginInfo").accessToken,
								'content-type': 'multipart/form-data'
							},
							filePath: images[i], // 要上传文件资源的路径
							name: 'file',
							success: (res) => {
								let data = JSON.parse(res.data)
								console.log("fileData", res, data)
								resolve(data.data.originUrl)
							},
							fail: (err) => {
								console.log(err);
								uni.showToast({
									title: "上传图片失败,gg,先别用了",
									icon: 'none'
								})
								reject(err)
							}

						})
					}))
				}
				return promiseArr
			},

			//提交表单
			submitform(e) {
				var that = this;
				var item = this.item;
				// console.log(item,item.description);
				// return ;
				// 判断物品描述是否为空
				if (item.description == '') {
					uni.showToast({
						title: '请填写物品描述',
						icon: 'error',
						success: () => {
							console.log('用户未填写物品描述');
							return false;
						}
					});
					return false;
				}
				// 判断是否选择时间
				if (item.date == '选择丢失时间' || item.date == '选择拾获时间') {
					item.date = null;
				}

				// 判断是否选择物品种类
				if (item.tag == null || item.tag == '') {
					uni.showToast({
						title: '请选择物品种类',
						icon: 'error',
						success: () => {
							console.log('用户未填写物品种类');
							return false;
						}
					});
					return false;
				}

				// 确认是否提交
				console.log('用户提交表单');

				uni.showModal({
					title: '提示',
					content: '是否确认发布',
					confirmText: '确认',
					success: (res) => {
						if (res.cancel) {
							console.log('用户取消发布');
							return false;
						}
						if (res.confirm) {

							console.log('用户点击确定');
							console.log('用户发布失物未提交前:', this.item);
							var images = this.images;

							// 图片上传完成后再进行发布
							try {
								uni.showLoading({
									title: '信息发布中',
								});


								var promiseArr = this.uploadImage(images)

								Promise.all(promiseArr).then((res) => {
									item.images = res;
									console.log('用户发布失物:', this.item, res);
									var itemPublishDTO = item
									this.$http({
										url: baseUrl + '/publishItem',
										method: 'POST',
										data: itemPublishDTO,
										header: {
											'content-type': 'application/json'
										}
									}).then((res) => {
										console.log("发布成功", res)
										this.reset()
										uni.showToast({
											'title': '发布成功',
											'icon': 'none'
										})
									}).catch((err) => {
										uni.showToast({
											title: "发布失败，请稍后再试",
											icon: 'none'
										})
									})
								}).catch((err) => {
									uni.showToast({
										title: "发布失败，请稍后再试",
										icon: 'none'
									})
								})

							} finally {
								uni.hideLoading()
							}
						}
					}
				});



			}
		},
	}
</script>
<style>
	/* pages/publish/publish.wxss */

	.title {
		display: flex;
	}

	.title .line {
		background-color: #ffeb37;
		height: 14rpx;
		border-radius: 35rpx;
		width: 80%;
	}

	.title .lose {
		margin: 30rpx;
		font-size: 38rpx;
	}

	.title .seek {
		margin: 30rpx;
		font-size: 38rpx;
	}

	.reset {
		height: 124rpx;
		margin-left: 190rpx;
		width: 100rpx;
	}

	.reset image {
		width: 100%;
		height: 100%;
	}

	.content {
		background-color: #fff;
		padding: 20rpx;
		/* height: 400rpx; */
		height: 350rpx;
		width: 85%;
		/* margin: 0 auto; */
		margin: 20rpx auto;
		border-radius: 20rpx;
		margin-top: 30rpx;
		box-shadow: 0rpx 1rpx 10rpx rgba(0, 0, 0, 0.09);
	}

	.title input {
		background-color: #e2e2e250;
		border-radius: 50rpx;
		margin: 0 auto;
		margin-top: 30rpx;
		height: 50rpx;
		padding: 20rpx;
		width: 85%;
	}

	.description-length {
		position: absolute;
		color: rgb(194, 189, 189);
		top: 150rpx;
		left: 550rpx;
		font-size: 31rpx;
	}

	.tag-list {
		width: 95%;
		margin: 0 auto;
		display: flex;
		justify-content: space-between;
	}

	.tag {
		background-color: #e2e2e250;
		width: 100rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
		padding: 10rpx;
		margin-top: 20rpx;
		text-align: center;
		color: #252525;
	}

	.tag1 {
		background-color: #ffeb37;
		width: 100rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
		padding: 10rpx;
		margin-top: 20rpx;
		text-align: center;
		color: #252525;
	}

	.text {
		display: flex;
		margin-left: 30rpx;
		margin-top: 50rpx;
	}

	.text .textFont {
		color: gray;
	}

	.text .input {
		margin-left: 50rpx;
	}

	.tip {
		margin-top: 40rpx;
		font-size: 24rpx;
		color: gray;
	}

	.addImg {
		width: 90%;
		height: 500rpx;
		background-color: #e2e2e29d;
		border-radius: 25rpx;
		font-size: 80rpx;
		line-height: 400rpx;
		text-align: center;
		margin: 40rpx;
		display: flex;
		flex-direction: column;
		flex-wrap: wrap;
	}

	.add {
		width: 40%;
		height: 200rpx;
		background-color: #e2e2e29d;
		border-radius: 25rpx;
		font-size: 80rpx;
		line-height: 200rpx;
		text-align: center;
		margin: 20rpx auto;
		position: relative;
	}

	.add image {
		height: 100%;
		width: 100%;
	}

	.del-icon {
		position: absolute;
		height: 70rpx;
		width: 50rpx;
		top: -60rpx;
		right: 0;
	}

	.del-icon image {
		width: 100%;
		height: 100%;
	}

	.tip-image {
		margin-top: 40rpx;
		font-size: 29rpx;
		color: gray;
		position: relative;
		bottom: 80rpx;
		left: 70rpx;
	}

	.supplement {
		background-color: #fff;
		padding: 20rpx;
		/* height: 400rpx; */
		height: 300rpx;
		width: 85%;
		/* margin: 0 auto; */
		margin: -10rpx auto;
		border-radius: 20rpx;

		box-shadow: 0rpx 1rpx 10rpx rgba(0, 0, 0, 0.09);
	}

	.location {
		margin-top: 20rpx;
		height: 60rpx;
		border: 1rpx lightgray;
		border-style: solid;
		border-width: 1rpx;
		background-color: rgba(242, 245, 247);
		border-radius: 10px;
	}

	.date {
		margin-top: 40rpx;
		height: 60rpx;
		border: 1rpx lightgray;
		border-style: solid;
		border-width: 1rpx;
		background-color: rgba(242, 245, 247);
		border-radius: 10px;
	}

	.submitButton {
		background-color: #ffeb37;
		margin: 0 auto;
		margin-top: 30rpx;
		border-radius: 30rpx;
		width: 80%;
		text-align: center;
		padding: 30rpx;
		margin-bottom: 100rpx;
	}
</style>